<template>
  <div>
    <p>重要四部曲: open, close, error, message</p>
    <el-input type="text" placeholder="请输入消息" v-model="msg" style="width: 300px" />
    <el-button @click="handleSendBtnClick">发送</el-button>
    <ul>
      <li v-for="item of msgList" :key="item.id">
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        </p>
        <p>消息：{{ item.msg }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import { useWebSocket } from "@/utils"

export default {
  name: "websocket",
  data() {
    return {
      msg: "",
      msgList: [],
      username: "xx",
      ws: null,
    }
  },
  methods: {
    handleSendBtnClick() {
      if (!this.msg.trim().length) {
        return
      }

      this.ws.send(
        JSON.stringify({
          id: new Date().getTime(),
          user: this.username,
          dateTime: new Date().getTime(),
          msg: this.msg,
        })
      )

      // 清空原来的数据
      this.msg = ""
    },

    handleMessage(e) {
      const _msgData = JSON.parse(e.data)
      this.msgList.push(_msgData)
    },
  },
  mounted() {
    if (!this.username) {
      router.push("/login")
      return
    }

    this.ws = useWebSocket(this.handleMessage)
  },
}
</script>
